﻿using Microsoft.Extensions.Logging;
using MQTTnet;
using MQTTnet.Client.Receiving;
using MQTTnet.Server;
using System;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Service.Mqtt.Callback.Handlers
{
    /// <summary>
    /// 收到客户端发布
    /// </summary>
    /// 
    public class MqttApplicationMessageReceivedHandler : IMqttApplicationMessageReceivedHandler
    {
        private readonly ILogger _logger;

        public MqttApplicationMessageReceivedHandler(ILogger<MqttServer> logger)
        {
            this._logger = logger;
        }

        public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(e.ClientId))
            {
                Console.WriteLine("### RECEIVED APPLICATION MESSAGE ###");
                Console.WriteLine($"+ Client = {e.ClientId}");
                Console.WriteLine($"+ Topic = {e.ApplicationMessage.Topic}");
                Console.WriteLine($"+ Payload = {((e.ApplicationMessage.Payload.Length > 0) ? Encoding.UTF8.GetString(e.ApplicationMessage.Payload) : "")}");
                Console.WriteLine($"+ QoS = {e.ApplicationMessage.QualityOfServiceLevel}");
                Console.WriteLine($"+ Retain = {e.ApplicationMessage.Retain}");
                Console.WriteLine();
             //   MqttServerService mqttServerService = (MqttServerService)ServiceLocator.Instance.GetService(typeof(MqttServerService));
              //  await mqttServerService.ForwardingAsync(e.ApplicationMessage.Topic.Split("/").LastOrDefault(), Encoding.UTF8.GetString(e.ApplicationMessage.Payload));
            }
        }

      
    }
}
